package httphandler

import (
	"context"
	"net/http"
	"strconv"

	_ctx "github.com/romapres2010/goapp/pkg/common/ctx"
	_http "github.com/romapres2010/goapp/pkg/common/httpservice"
	_log "github.com/romapres2010/goapp/pkg/common/logger"
)

// HealthHandler 是处理存活探针的处理器
func (s *Service) HealthHandler(w http.ResponseWriter, r *http.Request) {
	_log.Debug("START   ==================================================================================")

	// 启动处理器，错误返回被忽略
	_ = s.httpService.Process(true, "GET", w, r, func(ctx context.Context, requestBuf []byte, buf []byte) ([]byte, _http.Header, int, error) {
		requestID := _ctx.FromContextHTTPRequestID(ctx) // RequestID 通过上下文传递

		_log.Debug("START: requestID", requestID)

		// 构建响应
		header := _http.Header{}
		header[_http.HEADER_CUSTOM_ERR_CODE] = _http.HEADER_CUSTOM_ERR_CODE_SUCCESS
		header[_http.HEADER_CUSTOM_REQUEST_ID] = strconv.FormatUint(requestID, 10)

		// 从请求头读取参数并将它们复制到响应头
		for key := range r.Header {
			header[key] = r.Header.Get(key)
		}

		_log.Debug("SUCCESS", requestID)

		// 将输入缓冲区作为输出返回
		return requestBuf, header, http.StatusOK, nil
	})

	_log.Debug("SUCCESS ==================================================================================")
}
